package cn.windy.samary.module.abstracts;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyl
 * @date 2018/5/5 20:28
 */
public class AbstractEntity implements Serializable {

    public Map<String, Object> convertToMap(Object bean) {
        Class type = bean.getClass();
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String name = descriptor.getName();
                if (!"class".equalsIgnoreCase(name)) {
                    Method readMethod = descriptor.getReadMethod();
                    Object invoke = readMethod.invoke(bean);
                    if (invoke != null) {
                        map.put(name, invoke);
                    } else {
                        map.put(name, "");
                    }
                }
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


}
